package com.huike.web.controller.common;




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.huike.clues.service.ISysFileService;

import com.huike.common.core.controller.BaseController;
import com.huike.common.core.domain.AjaxResult;

import com.huike.common.utils.file.FileUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * 通用请求处理
 */
@RestController
public class CommonController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ISysFileService fileService;


    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file){
        try{
            // 上传文件路径
            return fileService.upload(file);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    @GetMapping("/common/download")
    //src//clues.xlsx
    public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName")String name) {
        try {
           // File file = new File("E:\develop\crm_projerct\crm\huike-admin\src\main\resources\clues.xlsx");
            File file = new File("huike-admin//src//main//resources//clues.xlsx");

            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData(name,
                    new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1"));
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 获取文件的字节数组 - 需要使用commons-io依赖包
            byte[] content = FileUtils.readFileToByteArray(file);
            return new ResponseEntity<>(content, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}